﻿
using MX.Core.Http.MVC.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;

namespace MX.Core.Http.MVC.Model
{

    /// <summary>
    /// 仅供Ajax 方式请求，返回JSON格式的结果 
    /// 引用 Microsoft.AspNetCore.Mvc.NewtonsoftJson
    /// 并用  services.AddControllers().AddNewtonsoftJson(); 注册
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MXResult : ApiReturnBase
    {
        public MXResult()
        {
        }
        [JsonProperty(PropertyName = "data")]
        public object Data { get; set; }


        /// <summary>
        /// 设置错误
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="errorMsg"></param>
        public void SetError(int errorCode, string errorMsg)
        {
            ErrorCode = errorCode;
            ErrorMsg = errorMsg;
        }

        /// <summary>
        /// 无结果返回
        /// </summary>
        /// <returns></returns>
        public JsonResult ReturnJson()
        {
            return ReturnJson(null);
        }

        /// <summary>
        /// 设置结果并返回JSON
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
		public JsonResult ReturnJson(object result)
        {
            if (result != null)
                Data = result;
            return new JsonResult(this, new JsonSerializerSettings()
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            })
            ;
        }

        /// <summary>
        /// 设置结果并返回JSON
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static JsonResult Json(object result)
        {
            return new MXResult() { Data = result }.ReturnJson();
        }
    }
}
